﻿using AutoMapper;
using MediatR;
using SmartApplication.Api.Applient.Command.Source;
using SmartApplication.ApiCode;
using SmartApplication.Domain.Entity;
using SmartApplication.Infrastructure.Instrument;
using System;
using Yitter.IdGenerator;

namespace SmartApplication.Api.Applient.CommandHandler.Source
{
    public class AddSourceHandler : IRequestHandler<AddSourceCommand, ApiResult<int>>
    {
        public AddSourceHandler(IBaseRepository<SourceModel> sourceRepository,IMapper mapper,IConfiguration configuration)
        {
            SourceRepository = sourceRepository;
            Mapper = mapper;
            Configuration = configuration;
        }

        public IBaseRepository<SourceModel> SourceRepository { get; }
        public IMapper Mapper { get; }
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 添加溯源基础数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddSourceCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();

            var sou = Mapper.Map<SourceModel>(request);
            sou.Id = YitIdHelper.NextId();
            var sc=DateTime.Now.ToString("yyyyMMddHHmmss");
            sou.Production = "SC" + sc;
            sou.ExpNumber = "SCPC" + sc;

            var ss=await SourceRepository.AddAsync(sou);
            if (ss>0)
            {
                res.Code = EnumCode.Success;
                res.Message = "添加溯源基础数据成功";
                res.Data = ss;
                await RedisHelper.DelAsync("rediskey");

                return res;
            }
            else
            {
                res.Code = EnumCode.Fail;
                res.Message = "添加溯源基础数据失败";
                res.Data = ss;
                return res;
            }
        }
    }
}
